﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 工艺流程服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class technologicalprocessService : IDynamicApiController, ITransient
{
     
    //technologicalprocess

    private readonly SqlSugarRepository<technologicalprocess> _technologicalprocessRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public technologicalprocessService(SqlSugarRepository<technologicalprocess> technologicalprocessRep, ISqlSugarClient sqlSugarClient)
    {
        _technologicalprocessRep = technologicalprocessRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询工艺流程 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询工艺流程")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<technologicalprocessOutput>> Page(PagetechnologicalprocessInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _technologicalprocessRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.superior_process_code.Contains(input.Keyword) || u.superior_process.Contains(input.Keyword) || u.lower_level_process_code.Contains(input.Keyword) || u.lower_level_process.Contains(input.Keyword) || u.current_process_code.Contains(input.Keyword) || u.current_process.Contains(input.Keyword) || u.completion_status.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.superior_process_code), u => u.superior_process_code.Contains(input.superior_process_code.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.superior_process), u => u.superior_process.Contains(input.superior_process.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.lower_level_process_code), u => u.lower_level_process_code.Contains(input.lower_level_process_code.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.lower_level_process), u => u.lower_level_process.Contains(input.lower_level_process.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.current_process_code), u => u.current_process_code.Contains(input.current_process_code.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.current_process), u => u.current_process.Contains(input.current_process.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.completion_status), u => u.completion_status.Contains(input.completion_status.Trim()))
            .WhereIF(input.technological_process_code != null, u => u.technological_process_code == input.technological_process_code)
            .LeftJoin<Routing>((u, technological_process_code) => u.technological_process_code == technological_process_code.Id)
            .Select((u, technological_process_code) => new technologicalprocessOutput
            {
                Id = u.Id,
                technological_process_code = u.technological_process_code,
                technological_process_codeFkDisplayName = $"{technological_process_code.routingname}",
                superior_process_code = u.superior_process_code,
                superior_process = u.superior_process,
                lower_level_process_code = u.lower_level_process_code,
                lower_level_process = u.lower_level_process,
                current_process_code = u.current_process_code,
                current_process = u.current_process,
                completion_status = u.completion_status,
                locking_state = u.locking_state,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取工艺流程详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取工艺流程详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<technologicalprocess> Detail([FromQuery] QueryByIdtechnologicalprocessInput input)
    {
        return await _technologicalprocessRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加工艺流程 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加工艺流程")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddtechnologicalprocessInput input)
    {
        var entity = input.Adapt<technologicalprocess>();
        return await _technologicalprocessRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新工艺流程 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新工艺流程")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdatetechnologicalprocessInput input)
    {
        var entity = input.Adapt<technologicalprocess>();
        await _technologicalprocessRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除工艺流程 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除工艺流程")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeletetechnologicalprocessInput input)
    {
        var entity = await _technologicalprocessRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _technologicalprocessRep.FakeDeleteAsync(entity);   //假删除
        //await _technologicalprocessRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除工艺流程 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除工艺流程")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeletetechnologicalprocessInput> input)
    {
        var exp = Expressionable.Create<technologicalprocess>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _technologicalprocessRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _technologicalprocessRep.FakeDeleteAsync(list);   //假删除
        //return await _technologicalprocessRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDatatechnologicalprocessInput input)
    {
        var technological_process_codeData = await _technologicalprocessRep.Context.Queryable<Routing>()
            .InnerJoinIF<technologicalprocess>(input.FromPage, (u, r) => u.Id == r.technological_process_code)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.routingname}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "technological_process_code", technological_process_codeData },
        };
    }
    
    /// <summary>
    /// 导出工艺流程记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出工艺流程记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PagetechnologicalprocessInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExporttechnologicalprocessOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "工艺流程导出记录");
    }
    
    /// <summary>
    /// 下载工艺流程数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载工艺流程数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExporttechnologicalprocessOutput>(), "工艺流程导入模板", (_, info) =>
        {
            if (nameof(ExporttechnologicalprocessOutput.technological_process_codeFkDisplayName) == info.Name) return _technologicalprocessRep.Context.Queryable<Routing>().Select(u => $"{u.routingname}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入工艺流程记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入工艺流程记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImporttechnologicalprocessInput, technologicalprocess>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 标识
                    var technological_process_codeLabelList = pageItems.Where(x => x.technological_process_codeFkDisplayName != null).Select(x => x.technological_process_codeFkDisplayName).Distinct().ToList();
                    if (technological_process_codeLabelList.Any()) {
                        var technological_process_codeLinkMap = _technologicalprocessRep.Context.Queryable<Routing>().Where(u => technological_process_codeLabelList.Contains($"{u.routingname}")).ToList().ToDictionary(u => $"{u.routingname}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.technological_process_code = technological_process_codeLinkMap.GetValueOrDefault(e.technological_process_codeFkDisplayName ?? "");
                            if (e.technological_process_code == null) e.Error = "标识链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<technologicalprocess>>();
                    
                    var storageable = _technologicalprocessRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.superior_process_code?.Length > 50, "上级工序编号长度不能超过50个字符")
                        .SplitError(it => it.Item.superior_process?.Length > 50, "上级工序长度不能超过50个字符")
                        .SplitError(it => it.Item.lower_level_process_code?.Length > 50, "下级工序编号长度不能超过50个字符")
                        .SplitError(it => it.Item.lower_level_process?.Length > 50, "下级工序长度不能超过50个字符")
                        .SplitError(it => it.Item.current_process_code?.Length > 50, "当前工序编号长度不能超过50个字符")
                        .SplitError(it => it.Item.current_process?.Length > 50, "当前工序长度不能超过50个字符")
                        .SplitError(it => it.Item.completion_status?.Length > 32, "完成状态长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
